/*
 * Copyright (c) 2021, 2021, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */
package com.oracle.truffle.espresso.processor.builders;

import java.util.ArrayList;
import java.util.List;

public final class JavadocBuilder extends AbstractCodeBuilder {
    public static final String JAVADOC_START = "/**";
    public static final String JAVADOC_MIDDLE = " * ";
    public static final String JAVADOC_END = " */";
    public static final String GENERATED_BY = "Generated by: ";
    public static final String LINK_OPEN = "{@link ";
    public static final String LINK_CLOSE = "}";

    public static String link(Object... parts) {
        StringBuilder sb = new StringBuilder();
        sb.append(LINK_OPEN);
        for (Object part : parts) {
            sb.append(part.toString());
        }
        sb.append(LINK_CLOSE);
        return sb.toString();
    }

    private final List<Object[]> lines = new ArrayList<>();

    public JavadocBuilder addLine(Object... parts) {
        lines.add(parts);
        return this;
    }

    public JavadocBuilder addGeneratedByLine(Object... parts) {
        Object[] genParts = new Object[parts.length + 3];
        genParts[0] = GENERATED_BY;
        genParts[1] = LINK_OPEN;
        System.arraycopy(parts, 0, genParts, 2, parts.length);
        genParts[genParts.length - 1] = LINK_CLOSE;
        lines.add(genParts);
        return this;
    }

    @Override
    void buildImpl(IndentingStringBuilder sb) {
        sb.appendLine(JAVADOC_START);
        for (Object[] parts : lines) {
            sb.append(JAVADOC_MIDDLE);
            for (Object part : parts) {
                if (part instanceof AbstractCodeBuilder) {
                    ((AbstractCodeBuilder) part).buildImpl(sb);
                } else {
                    sb.append(part.toString());
                }
            }
            sb.appendLine();
        }
        sb.appendLine(JAVADOC_END);
    }
}
